/* Copyright (C) 2010 Moritz Bitsch
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 *
 * Author:
 *      Moritz Bitsch <moritzbitsch@googlemail.com>
 */

namespace Webappi {
	public class TempFile {
		public string filename{public get; private set;}
		public FileStream file;

		public TempFile.with_template(string template) throws FileError {
			string name = Path.build_filename(Environment.get_tmp_dir(), template);
			var tmpFile = Posix.mkstemp(name);

			if (tmpFile < 0) {
				throw new FileError.FAILED("Can't create temp file");
			}

			this.filename = name;
			this.file = FileStream.fdopen(tmpFile, "w+");
			dprint(LogLevel.Insane, "tempfile", "init");
		}

		~TempFile() {
			dprint(LogLevel.Insane, "tempfile", "cleanup");
			FileUtils.remove(filename);
		}

		public void putc(char c) {
			this.file.putc(c);
		}

		public void rewind() {
			this.file.rewind();
		}

		public void flush() {
			this.file.flush();
		}

		public static extern new void unref(void* self);
	}
}